package pl.pawluk.inz.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.red5.server.adapter.ApplicationAdapter;
import org.red5.server.api.IConnection;
import org.red5.server.api.Red5;
import org.red5.server.api.scope.IScope;
import org.red5.server.api.stream.IBroadcastStream;
import org.red5.server.stream.ClientBroadcastStream;

public class Application extends ApplicationAdapter{
	private ClientManager clientManager = new ClientManager("userList", false);
    private Map<String, String> connectedClients = new ConcurrentHashMap<java.lang.String, java.lang.String>();
	@Override
	public synchronized boolean connect(IConnection conn, IScope scope,
			Object[] params) {
		//Verify is username is in params
		if(params == null || params.length == 0){
			rejectClient("No username was provided");
		}
		if(!super.connect(conn, scope, params)){
			return false;
		}
		String username = params[0].toString();
		String uid = conn.getClient().getId();
		//add the username to the collection
		connectedClients.put(uid, username);
		clientManager.addClient(scope, username, uid);
		return true;
	}

	@Override
	public synchronized void disconnect(IConnection conn, IScope scope) {
		String uid = conn.getClient().getId();
		connectedClients.remove(uid);
        clientManager.removeClient(scope, uid);
		super.disconnect(conn, scope);
	}
	public ArrayList<String> getConnectedClients(){
		return new ArrayList<String>(connectedClients.values());
	}

    public String getClient(String uid) {
        return connectedClients.get(uid);
    }

}
